package com.littleken.dao.impl;

import com.littleken.config.DBConfig;
import com.littleken.dao.UserDao;
import com.littleken.entity.User;
import com.littleken.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    Connection conn = null;//todo:连接数据库
    public UserDaoImpl() {
        //todo:密码加密
        conn = DBUtil.getConn();
    }
    private static User getUser(ResultSet resultSet){
        User user = null;
        try {
            if (resultSet.next()){
                Integer Id = resultSet.getInt(1);
                String Username = resultSet.getString(2);
                String Password =resultSet.getString(3);
                String Emain = resultSet.getString(4);
                String Phone = resultSet.getString(5);
                Integer Grade = resultSet.getInt(6);
                user = new User(Id,Username,Password,Emain,Phone,Grade);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }


    /**
     * 查询用户密码是否正确
     * @param checkUser
     * @return
     */
    @Override
    public User checkUser(User checkUser) {
        User u = null;
        try{//防止传过来的user有空，直接返回null
            if(checkUser==null || checkUser.getUsername()==null||checkUser.getPassword()==null){
                return null;
            }
        }catch (Exception e){
            return null;
        }

        try {
            String sql = "select * from user where Username=?and Password = ?";
            PreparedStatement p = this.conn.prepareStatement(sql);
            p.setString(1,checkUser.getUsername());
            p.setString(2,checkUser.getPassword());
            ResultSet resultSet = p.executeQuery();
            u = getUser(resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u;
    }

    @Override
    public List<User> getAllUser() {
        List<User> users = new ArrayList<>();
        User u = null;
        try {
            String sql = "select * from user";
            PreparedStatement p = this.conn.prepareStatement(sql);
            ResultSet resultSet = p.executeQuery();
            while (resultSet.next()){
                resultSet.previous();
                u = getUser(resultSet);
                users.add(u);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (users.size()==0){
            users=null;
        }
        return users;
    }

}

